<template>
  <ArtTableFullScreen>
    <div id="table-full-screen">
      <el-card shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton :icon="Plus" @click="showDialog('add')" v-ripple>新增</ElButton>
            <el-select
              style="width: 200px; margin-left: 10px"
              v-model="queryParams.cate_id"
              @change="getPage"
            >
              <el-option
                v-for="type in typeList"
                :key="type.id"
                :label="type.name"
                :value="type.id"
              ></el-option>
            </el-select>
          </template>
        </ArtTableHeader>
        <art-table
          :data="tableData"
          :loading="loading"
          v-model:currentPage="queryParams.page"
          v-model:pageSize="queryParams.size"
          :total="total"
          @size-change="getPage"
          @current-change="getPage"
        >
          <template #default>
            <el-table-column v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </art-table>

        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '添加内容' : '编辑内容'"
          width="40%"
        >
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="分类" prop="cate_id">
              <el-select v-model="formData.cate_id" style="width: 200px">
                <el-option
                  v-for="type in typeList"
                  :key="type.id"
                  :label="type.name"
                  :value="type.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="封面" prop="cover">
              <ArtImageUpload v-model:files="formData.cover"></ArtImageUpload>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <el-input type="textarea" v-model="formData.content" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input type="textarea" v-model="formData.desc" placeholder="请输入描述" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">提交</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { ElButton, FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { Plus } from '@element-plus/icons-vue'
  import type { FormRules } from 'element-plus'
  import { ContentService } from '@/api/common'
  import { TypeService } from '@/api/common/type'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import ArtImagePreview from '@/components/image/ArtImagePreview.vue'
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)
  const tableData = ref<any>([])

  const formData = reactive({
    title: '',
    cover: '',
    content: '',
    desc: '',
    cate_id: ''
  })
  const total = ref(0)
  const queryParams = reactive({
    page: 1,
    size: 10,
    cate_id: 2 // 热量
  })
  const typeList = ref<any>([])
  const pid = 2
  onMounted(() => {
    getTypes().then(() => {
      getPage()
    })
  })
  // 刷新
  const handleRefresh = () => {
    getPage()
  }
  // 列配置
  const columnOptions = [
    { label: '勾选', type: 'selection' },
    { label: 'ID', prop: 'id' },
    { label: '标题', prop: 'title' },
    { label: '封面', prop: 'cover' },
    { label: '内容', prop: 'content' },
    { label: '描述', prop: 'desc' },
    { label: '创建日期', prop: 'create_time' },
    { label: '操作', prop: 'operation' }
  ]
  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    // { type: 'selection' }, // 勾选列
    // { type: 'expand', label: '展开', width: 80 }, // 展开列
    { type: 'index', label: '序号', width: 80, align: 'center' }, // 序号列
    { prop: 'id', label: 'ID', align: 'center' },
    { prop: 'title', label: '标题' },
    {
      prop: 'cover',
      label: '封面',
      formatter: (row: any) => {
        return h(ArtImagePreview, { src: row.cover })
      }
    },
    { prop: 'content', label: '内容' },
    { prop: 'desc', label: '描述' },
    { prop: 'create_time', label: '创建日期', sortable: true },
    {
      prop: 'operation',
      label: '操作',
      width: 200,
      align: 'center',
      fixed: 'right', // 固定在右侧
      // disabled: true,
      formatter: (row: any) => {
        return h('div', [
          h(ArtButtonTable, {
            type: 'edit',
            onClick: () => showDialog('edit', row)
          }),
          h(ArtButtonTable, {
            type: 'delete',
            onClick: () => deleteTableRow(row)
          })
        ])
      }
    }
  ])
  // 获取分类
  const getTypes = async () => {
    const res = await TypeService.getChildCate(pid)
    queryParams.cate_id = res.data[0].id
    typeList.value = res.data
  }
  // 获取商品列表
  const getPage = async () => {
    loading.value = true
    const res = await ContentService.getListContent(queryParams)
    total.value = res.data.total
    tableData.value = res.data.data
    loading.value = false
  }
  const showDialog = (type: string, row?: any) => {
    if (type === 'edit' && row) {
      formData.id = row.id
      formData.title = row.title
      formData.cover = row.cover
      formData.content = row.content
      formData.desc = row.desc
      formData.cate_id = row.cate_id
    } else {
      formData.id = undefined
      formData.title = ''
      formData.content = ''
      formData.desc = ''
      formData.cover = ''
      formData.cate_id = ''
    }
    dialogVisible.value = true
    dialogType.value = type
  }

  const deleteTableRow = (row: any) => {
    ElMessageBox.confirm('确定要删除该列吗？', '删除列表', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return ContentService.deleteContent(row.id)
      })
      .then(() => {
        getPage()
        ElMessage.success('删除成功')
      })
  }

  const rules = reactive<FormRules>({
    cate_id: [{ required: true, message: '请选择分类', trigger: 'blur' }],
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    cover: [{ required: true, message: '请选择封面', trigger: 'blur' }],
    content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
    desc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = () => {
    if (!formRef.value) return
    formRef.value.validate(async (valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          await ContentService.addContent(formData)
        } else {
          await ContentService.updateContent(formData)
        }
        await getPage()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
      }
    })
  }
</script>
